const app = getApp();

console.log(app);







// const init = () => {

//     BLEInit()

// }

export default function BLE() {

    let interval = setinterval(function() {
        BLEInit()
    }, 5000)






}














/****************1.蓝牙初始化***************/
const BLEInit = () => {
    wx.openBluetoothAdapter({
        success: (res) => {

            BLEState()
        },
        fail: (res) => {
            app.Toast('请打开蓝牙和定位功能!')
        }
    })
}
/****************2.获取蓝牙状态***************/
const BLEState = () => {
    wx.getBluetoothAdapterState({
        success: (res) => {
            BLESearch()
        },
        fail: (res) => {
            app.Toast('蓝牙状态错误,请重新打开小程序')
        }
    })
}
/****************3.搜索附近蓝牙***************/
const BLESearch = () => {
    wx.startBluetoothDevicesDiscovery({
        //0000FFF0-0000-1000-8000-00805F9B34FB
        services: ['0000FFF0-0000-1000-8000-00805F9B34FB'], //蓝牙设备id
        success: (res) => {
            console.log('开始扫描附近设备!', res);
            BLEGetDevices()
        }
    });
}
/****************4.获取蓝牙设备***************/
const BLEGetDevices = () => {
    wx.getBluetoothDevices({
        success: (res) => {
            console.log('已经发现的所有蓝牙设备', res);
            if (res.devices[0]) {
                this.BLEConnect(res.devices[0]);
            } else {
                wx.showLoading({
                    title: '正在搜索蓝牙中，请稍后～',
                    mask: true
                });
            }
        }
    })
    //发现蓝牙新设备事件
    wx.onBluetoothDeviceFound(res => {
        res.devices.forEach(v => {
            console.log('发现新设备', res);
            if (v.name == 'BT201-BLE' && !this.data.deviceId) {
                this.BLEConnect(v)
            }
        })

    })
}
/****************5.链接蓝牙***************/
const BLEConnect = () => {
    wx.createBLEConnection({
        deviceId: BLE.deviceId,
        success: (res) => {
            app.Toast('连接成功～', 'success');
            wx.stopBluetoothDevicesDiscovery(); //  停止搜索蓝牙
            this.BLEGetservice(BLE);
            this.setData({
                deviceId: BLE.deviceId
            })
        },
        fail: () => {
            app.Toast('连接失败!')
        },
    })

}
/****************6.获取蓝牙服务***************/
const BLEGetservice = () => {
    wx.getBLEDeviceServices({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: BLE.deviceId,
        success: (res) => {
            console.log('获取蓝牙服务', res);
            this.BLEGetCharacteristics(BLE, res.services[0]);
            this.setData({
                serviceId: res.services[0].uuid,
            })
        }
    })
}
/****************7.获取所有的特征值***************/
const BLEGetCharacteristics = (BLE, SERVER) => {
    wx.getBLEDeviceCharacteristics({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: BLE.deviceId,
        // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
        serviceId: SERVER.uuid,
        success: (res) => {
            console.log('获取所有的特征值', res)
            this.BLECharacteristicValueChange(BLE, SERVER, res.characteristics);
            this.setData({
                characteristicId: res.characteristics[0].uuid
            })
        }
    })
}
/****************8.启用特征值变化***************/
const BLECharacteristicValueChange = (BLE, SERVER, CHARACTERISTIC) => {
    wx.notifyBLECharacteristicValueChange({
        state: true,
        deviceId: BLE.deviceId,
        serviceId: SERVER.uuid,
        characteristicId: CHARACTERISTIC[0].uuid,
        success: (res) => {
            console.log('特征值发生变化', res)
            this.BLEDataRecieve()
        },
        fail: (err) => {
            console.log('启动notify失败:' + JSON.stringify(err));
        },
    })
}
/****************9.接收蓝牙的返回数据***************/
const BLEDataRecieve = () => {
    wx.onBLECharacteristicValueChange((res) => {
        console.log('接受数据', res);
    })
}
/****************10.向蓝牙写入数据***************/
const BLEDataWrite = (r, g, b) => {
    let buffer = new ArrayBuffer(10)
    let dataView = new DataView(buffer)
    let arr = ['46', '10', '0', '0', '1', '10', r, g, b, '50'];
    arr.forEach((v, i) => {
        dataView.setUint8(i, v)
    })
    wx.writeBLECharacteristicValue({
        // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
        deviceId: this.data.deviceId,
        // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
        serviceId: this.data.serviceId,
        // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
        characteristicId: this.data.characteristicId,
        // 这里的value是ArrayBuffer类型
        value: buffer,
        success(res) {
            console.log('写入蓝牙成功', res.errMsg);
            app.Toast('改变颜色成功！', 'success')
        },
        fali(err) {
            console.log('写入蓝牙失败', err);
            app.Toast('改变颜色失败')
        },
        complete(e) {
            console.log('写入蓝牙', e);
        }
    })
}